package com.isay.frameworklib.widget.tab;

import android.content.Context;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import java.util.List;

import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;

/**
 * tab widget
 * Created by cywu4 on 2018/8/6.
 */
public class FragmentTabWidget extends LinearLayout {

    private int mSelectedTabIndex = -1;
    private OnTabSelectedListener mTabReselectedListener;


    public FragmentTabWidget(Context context) {
        this(context, null);
    }

    public FragmentTabWidget(Context context, AttributeSet attrs) {
        super(context, attrs);
        setHorizontalScrollBarEnabled(false);
        this.setGravity(Gravity.CENTER_HORIZONTAL);
        this.setOrientation(HORIZONTAL);
        setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
    }


    /**
     * tab 点击回调接口
     */
    public interface OnTabSelectedListener {
        void onTabSelected(int position);
    }

    public void setOnTabReselectedListener(OnTabSelectedListener listener) {
        mTabReselectedListener = listener;
    }

    public void setCurrentTab(int index) {
        if (index == mSelectedTabIndex) {
            return;
        }
        if (mSelectedTabIndex < 0) {
            mSelectedTabIndex = 0;
        }
        AppTabView child = (AppTabView) this.getChildAt(mSelectedTabIndex);
        if (child == null) {
            return;
        }
        // 改变tab的选中状态
        child.setSelectedStatus(false);
        AppTabView currChild = (AppTabView) this.getChildAt(index);
        if (currChild != null) {
            currChild.setSelectedStatus(true);
        }
        mSelectedTabIndex = index;
    }

    public void clearTabAll() {
        removeAllViews();
    }

    public void addTabAll(List<AppTabInfo> list) {
        for (int i = 0, size = list.size(); i < size; i++) {
            addTab(i, list.get(i));
        }
    }

    public void addTab(int index, AppTabInfo info) {
        AppTabView tabView = new AppTabView(getContext(), info, index);
        tabView.setFocusable(true);
        tabView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                AppTabView tabView = (AppTabView) v;
                int index = tabView.getIndex();
                if (index == mSelectedTabIndex) {
                    return;
                }
                setCurrentTab(index);
                if (mTabReselectedListener != null) {
                    mTabReselectedListener.onTabSelected(index);
                }
            }
        });
        addView(tabView, new LayoutParams(0, MATCH_PARENT, 1));
    }


}
